﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QFile>
#include "MyHttp.h"
#include <QDesktopServices>
#include <QThreadPool>
#include <QtConcurrent>
#include "DownloadTsFileManager.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QHBoxLayout* playout = new QHBoxLayout(ui->centralwidget);
    ui->centralwidget->setLayout(playout);
    playout->addWidget(ui->widget_5);

    ui->horizontalLayout_5->insertStretch(0);
    ui->horizontalLayout_4->insertStretch(0);
    ui->horizontalLayout_4->addStretch();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    bool isEnabled = ui->pushButton->isEnabled();
    if (!isEnabled)
    {
        return;
    }
    ui->pushButton->setEnabled(false);

    QFutureWatcher<void> *futureWatcher = new  QFutureWatcher<void>(this);
    connect(futureWatcher, SIGNAL(finished()), this, SLOT(slotFutureFinished()));
    connect(futureWatcher, SIGNAL(finished()), futureWatcher, SLOT(deleteLater()));
    futureWatcher->setFuture(QtConcurrent::run([&]()
    {
        QString sUrl = ui->lineEdit->text();
        QString sPath = ui->lineEditSave->text();
        bool isDelTemp = ui->checkBox->checkState();

        DownloadTsFileManager mgr(sUrl, sPath);
        mgr.setProperty("isDeleteTempFiles", isDelTemp);
        connect(&mgr, SIGNAL(sigDownMessage(QString)), this, SLOT(slotDownMessage(QString)));
        mgr.purgeDownloadResult();
        int statas = mgr.getGlobalStatas();
        if (statas != 0)
        {
            mgr.DownTsFiles();
        }
        else
        {
            emit mgr.sigDownMessage(TR("请检查aria2的是否运行正常！！！"));
        }
    }));
}

void MainWindow::slotFutureFinished()
{
    ui->pushButton->setEnabled(true);
}

void MainWindow::slotDownMessage(QString msg)
{
    ui->listWidget->addItem(msg);
    ui->listWidget->setCurrentRow(ui->listWidget->count()-1);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    {
        QStringList args;
        args << "/F" << "/PID" << QString::number(QApplication::applicationPid()) << "/T";
        QProcess::startDetached(QString("TASKKILL"), args);
    }

    QMainWindow::closeEvent(event);
}


//下载控制台
void MainWindow::on_pushButton_3_clicked()
{
    QUrl url(QString("http://aria2c.com/"));
    QDesktopServices::openUrl(url);
}
//OK资源网
void MainWindow::on_pushButton_2_clicked()
{
//    //https://cj.okzy.tv/
//    //http://www.kk2w.cc/
//    QUrl url(QString("https://www.okzy.co/"));
//    QDesktopServices::openUrl(url);



}


